﻿using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WMS.Controllers
{
    /// <summary>
    /// 销售退货控制器
    /// </summary>
    public class OmSalesReturnController : Controller
    {
        private readonly IOmSalesReturnDetailService _omSalesReturnDetailService;
        private readonly IOmSalesReturnService _omSalesReturnService;
        private readonly IBiCustomerService _biCustomerService;

        public OmSalesReturnController(
            IOmSalesReturnDetailService omSalesReturnDetailService,
            IOmSalesReturnService omSalesReturnService,
            IBiCustomerService biCustomerService)
        {
            _omSalesReturnDetailService = omSalesReturnDetailService;
            _omSalesReturnService = omSalesReturnService;
            _biCustomerService = biCustomerService;
        }

        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取所有销售退货数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetAllAsync()
        {
            try
            {
                var result = await _omSalesReturnService.GetAllAsync();
                if (result != null && result.Any())
                {
                    var data = new List<object>();

                    foreach (var r in result)
                    {
                        // 过滤已删除的数据
                        if (r.IsDelete == "Y") continue;

                        var customer = await _biCustomerService.GetByIdAsync(r.CustomerId);

                        data.Add(new
                        {
                            salesReturnId = r.SalesReturnId,
                            returnOrderNo = r.ReturnOrderNo,
                            customerId = r.CustomerId,
                            customerName = customer?.CustomerName ?? "未知客户",
                            sellerBy = r.SellerBy,
                            returnDate = r.ReturnDate,
                            returnReason = r.ReturnReason,
                            orderStatus = r.OrderStatus,
                            auditorBy = r.AuditorBy,
                            auditorTime = r.AuditorTime,
                            auditorComment = r.AuditorComment,
                            isDelete = r.IsDelete,
                            createBy = r.CreateBy,
                            createTime = r.CreateTime,
                            updateBy = r.UpdateBy,
                            updateTime = r.UpdateTime,
                            remarks = r.Remarks
                        });
                    }

                    return Ok(new { code = 200, data = data, msg = "查询成功" });
                }
                else
                {
                    return Ok(new { code = 200, data = new List<object>(), msg = "暂无数据" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 详细信息页面
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <param name="pwd">密码参数</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Details(long id, string pwd)
        {
            ViewBag.SalesReturnId = id;
            return View();
        }

        /// <summary>
        /// 获取销售退货单详细信息
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Details(long id)
        {
            try
            {
                var salesReturn = await _omSalesReturnService.GetByIdAsync(id);
                if (salesReturn != null && salesReturn.IsDelete != "Y")
                {
                    var customer = await _biCustomerService.GetByIdAsync(salesReturn.CustomerId);

                    // 获取退货明细
                    var returnDetails = await _omSalesReturnDetailService.GetAllAsync();
                    var details = returnDetails?.Where(d => d.SalesReturnId == id && d.IsDelete != "Y").ToList() ?? new List<OmSalesReturnDetail>();

                    var result = new
                    {
                        // 主单信息
                        salesReturnId = salesReturn.SalesReturnId,
                        returnOrderNo = salesReturn.ReturnOrderNo,
                        customerId = salesReturn.CustomerId,
                        customerName = customer?.CustomerName ?? "未知客户",
                        sellerBy = salesReturn.SellerBy,
                        returnDate = salesReturn.ReturnDate,
                        returnReason = salesReturn.ReturnReason,
                        orderStatus = salesReturn.OrderStatus,
                        auditorBy = salesReturn.AuditorBy,
                        auditorTime = salesReturn.AuditorTime,
                        auditorComment = salesReturn.AuditorComment,
                        isDelete = salesReturn.IsDelete,
                        createBy = salesReturn.CreateBy,
                        createTime = salesReturn.CreateTime,
                        updateBy = salesReturn.UpdateBy,
                        updateTime = salesReturn.UpdateTime,
                        remarks = salesReturn.Remarks,

                        // 明细信息
                        returnDetails = details.Select(d => new
                        {
                            salesReturnDetailId = d.SalesReturnDetailId,
                            salesReturnId = d.SalesReturnId,
                            goodsCode = d.GoodsCode,
                            goodsTypeId = d.GoodsTypeId,
                            returnAmount = d.ReturnAmount,
                            orderQuantity = d.OrderQuantity,
                            outboundQty = d.OutBboundQty,
                            unshippedQty = d.UnshippedQty,
                            isDelete = d.IsDelete,
                            attachmentId = d.AttachmentId,
                            remarks = d.Remarks
                        })
                    };

                    return Ok(new { code = 200, data = result, msg = "查询成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "销售退货单不存在或已被删除" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 创建页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 创建销售退货单
        /// </summary>
        /// <param name="model">销售退货创建模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] OmSalesReturnCreateModel model)
        {
            try
            {
                if (model == null || model.SalesReturn == null)
                {
                    return Ok(new { code = 400, msg = "请求数据不能为空" });
                }

                // 设置创建信息
                model.SalesReturn.CreateTime = DateTime.Now;
                model.SalesReturn.UpdateTime = DateTime.Now;
                model.SalesReturn.IsDelete = "N";

                // 如果未指定状态，默认为草稿
                if (string.IsNullOrEmpty(model.SalesReturn.OrderStatus))
                {
                    model.SalesReturn.OrderStatus = "0"; // 草稿状态
                }

                // 1. 创建销售退货主单
                var result = await _omSalesReturnService.CreateAsync(model.SalesReturn);

                if (result > 0)
                {
                    // 2. 创建销售退货明细
                    if (model.ReturnDetails != null && model.ReturnDetails.Any())
                    {
                        foreach (var detail in model.ReturnDetails)
                        {
                            detail.SalesReturnId = model.SalesReturn.SalesReturnId;
                            detail.IsDelete = "N";
                            await _omSalesReturnDetailService.CreateAsync(detail);
                        }
                    }

                    return Ok(new { code = 200, msg = "创建成功", data = new { salesReturnId = model.SalesReturn.SalesReturnId } });
                }
                else
                {
                    return Ok(new { code = 500, msg = "销售退货单创建失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"创建失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 修改页面 
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <returns></returns>
        public IActionResult Edit(long id)
        {
            ViewBag.SalesReturnId = id;
            return View();
        }

        /// <summary>
        /// 获取编辑数据
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetEditData(long id)
        {
            try
            {
                var salesReturn = await _omSalesReturnService.GetByIdAsync(id);
                if (salesReturn != null && salesReturn.IsDelete != "Y")
                {
                    var customer = await _biCustomerService.GetByIdAsync(salesReturn.CustomerId);

                    // 获取退货明细
                    var returnDetails = await _omSalesReturnDetailService.GetAllAsync();
                    var details = returnDetails?.Where(d => d.SalesReturnId == id && d.IsDelete != "Y").ToList() ?? new List<OmSalesReturnDetail>();

                    var result = new
                    {
                        // 主单信息
                        salesReturn = new
                        {
                            salesReturnId = salesReturn.SalesReturnId,
                            returnOrderNo = salesReturn.ReturnOrderNo,
                            customerId = salesReturn.CustomerId,
                            customerName = customer?.CustomerName ?? "未知客户",
                            sellerBy = salesReturn.SellerBy,
                            returnDate = salesReturn.ReturnDate,
                            returnReason = salesReturn.ReturnReason,
                            orderStatus = salesReturn.OrderStatus,
                            auditorBy = salesReturn.AuditorBy,
                            auditorTime = salesReturn.AuditorTime,
                            auditorComment = salesReturn.AuditorComment,
                            isDelete = salesReturn.IsDelete,
                            createBy = salesReturn.CreateBy,
                            createTime = salesReturn.CreateTime,
                            updateBy = salesReturn.UpdateBy,
                            updateTime = salesReturn.UpdateTime,
                            remarks = salesReturn.Remarks
                        },

                        // 明细信息
                        returnDetails = details.Select(d => new
                        {
                            salesReturnDetailId = d.SalesReturnDetailId,
                            salesReturnId = d.SalesReturnId,
                            goodsCode = d.GoodsCode,
                            goodsTypeId = d.GoodsTypeId,
                            returnAmount = d.ReturnAmount,
                            orderQuantity = d.OrderQuantity,
                            outboundQty = d.OutBboundQty,
                            unshippedQty = d.UnshippedQty,
                            isDelete = d.IsDelete,
                            attachmentId = d.AttachmentId,
                            remarks = d.Remarks
                        })
                    };

                    return Ok(new { code = 200, data = result, msg = "查询成功" });
                }
                else
                {
                    return Ok(new { code = 404, msg = "销售退货单不存在或已被删除" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"查询异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 修改提交
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <param name="model">销售退货更新模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Edit(long id, [FromBody] OmSalesReturnUpdateModel model)
        {
            try
            {
                if (model == null || model.SalesReturn == null)
                {
                    return Ok(new { code = 400, msg = "请求数据不能为空" });
                }

                // 验证ID一致性
                if (model.SalesReturn.SalesReturnId != id)
                {
                    return Ok(new { code = 400, msg = "ID不匹配" });
                }

                // 设置更新信息
                model.SalesReturn.UpdateTime = DateTime.Now;

                // 1. 更新销售退货主单
                var result = await _omSalesReturnService.UpdateAsync(model.SalesReturn);

                if (result > 0)
                {
                    // 2. 处理销售退货明细
                    if (model.ReturnDetails != null)
                    {
                        // 获取现有明细
                        var existingDetails = await _omSalesReturnDetailService.GetAllAsync();
                        var currentDetails = existingDetails?.Where(d => d.SalesReturnId == id && d.IsDelete != "Y").ToList() ?? new List<OmSalesReturnDetail>();

                        // 处理明细更新：这里简化处理，实际可能需要更复杂的逻辑
                        foreach (var detail in model.ReturnDetails)
                        {
                            if (detail.SalesReturnDetailId == 0)
                            {
                                // 新增明细
                                detail.SalesReturnId = id;
                                detail.IsDelete = "N";
                                await _omSalesReturnDetailService.CreateAsync(detail);
                            }
                            else
                            {
                                // 更新现有明细
                                await _omSalesReturnDetailService.UpdateAsync(detail);
                            }
                        }

                        // 处理删除的明细（逻辑删除）
                        var updatedDetailIds = model.ReturnDetails.Where(d => d.SalesReturnDetailId > 0).Select(d => d.SalesReturnDetailId);
                        var detailsToDelete = currentDetails.Where(d => !updatedDetailIds.Contains(d.SalesReturnDetailId));
                        foreach (var detail in detailsToDelete)
                        {
                            detail.IsDelete = "Y";
                            await _omSalesReturnDetailService.UpdateAsync(detail);
                        }
                    }

                    return Ok(new { code = 200, msg = "更新成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"更新异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 删除销售退货单（逻辑删除）
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete(long id)
        {
            try
            {
                var salesReturn = await _omSalesReturnService.GetByIdAsync(id);
                if (salesReturn == null || salesReturn.IsDelete == "Y")
                {
                    return Ok(new { code = 404, msg = "销售退货单不存在或已被删除" });
                }

                // 检查状态：只有草稿和待审核状态可以删除
                if (salesReturn.OrderStatus != "0" && salesReturn.OrderStatus != "1")
                {
                    return Ok(new { code = 400, msg = "当前状态不允许删除" });
                }

                // 逻辑删除主单
                salesReturn.IsDelete = "Y";
                salesReturn.UpdateTime = DateTime.Now;
                var result = await _omSalesReturnService.UpdateAsync(salesReturn);

                if (result > 0)
                {
                    // 逻辑删除关联的明细
                    var returnDetails = await _omSalesReturnDetailService.GetAllAsync();
                    var details = returnDetails?.Where(d => d.SalesReturnId == id && d.IsDelete != "Y").ToList();
                    if (details != null && details.Any())
                    {
                        foreach (var detail in details)
                        {
                            detail.IsDelete = "Y";
                            await _omSalesReturnDetailService.UpdateAsync(detail);
                        }
                    }

                    return Ok(new { code = 200, msg = "删除成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "删除失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"删除异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CustomerAll()
        {
            try
            {
                var data = await _biCustomerService.GetAllAsync();

                var result = (data ?? new List<BiCustomer>())
                            .Where(c => c.IsDelete != "Y")
                            .Select(c => new
                            {
                                Id = c.CustomerId,
                                Name = c.CustomerName
                            }).ToList();

                return Ok(new { code = 200, data = result, msg = "获取成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"获取客户信息异常：{ex.Message}" });
            }
        }

        /// <summary>
        /// 更新销售退货单状态
        /// </summary>
        /// <param name="id">销售退货单ID</param>
        /// <param name="status">状态</param>
        /// <param name="auditorComment">审核意见</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateStatus(long id, string status, string auditorComment = "")
        {
            try
            {
                var salesReturn = await _omSalesReturnService.GetByIdAsync(id);
                if (salesReturn == null || salesReturn.IsDelete == "Y")
                {
                    return Ok(new { code = 404, msg = "销售退货单不存在或已被删除" });
                }

                salesReturn.OrderStatus = status;
                salesReturn.UpdateTime = DateTime.Now;

                // 如果是审核相关操作，记录审核信息
                if (status == "1" || status == "2" || status == "3")
                {
                    salesReturn.AuditorTime = DateTime.Now;
                    salesReturn.AuditorComment = auditorComment;
                    // 这里应该从登录用户信息中获取审核人
                    // salesReturn.AuditorBy = User.Identity.Name;
                }

                var result = await _omSalesReturnService.UpdateAsync(salesReturn);

                if (result > 0)
                {
                    return Ok(new { code = 200, msg = "状态更新成功" });
                }
                else
                {
                    return Ok(new { code = 500, msg = "状态更新失败" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new { code = 500, msg = $"状态更新异常：{ex.Message}" });
            }
        }
    }

    /// <summary>
    /// 销售退货创建模型
    /// </summary>
    public class OmSalesReturnCreateModel
    {
        public OmSalesReturn SalesReturn { get; set; }
        public List<OmSalesReturnDetail> ReturnDetails { get; set; }
    }

    /// <summary>
    /// 销售退货更新模型
    /// </summary>
    public class OmSalesReturnUpdateModel
    {
        public OmSalesReturn SalesReturn { get; set; }
        public List<OmSalesReturnDetail> ReturnDetails { get; set; }
    }
}